package io.cp.connector.gateway.config;

import java.util.Objects;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import reactor.core.publisher.Mono;

@Configuration
public class RateLimiterConfig {
	
	private static Log log = LogFactory.getLog(RateLimiterConfig.class);
	
	/**
	@Bean
	public KeyResolver userKeyResolver() {
	   return exchange -> Mono.just( Objects.requireNonNull(exchange.getRequest().getQueryParams().getFirst("userId")) );
	}
	
	@Bean
	public KeyResolver ipKeyResolver() {
	   return exchange -> Mono.just( Objects.requireNonNull( exchange.getRequest().getRemoteAddress().getHostName() ) );
	}
	*/
	
	@Primary
    @Bean(value = "remoteAddrKeyResolver")
    public KeyResolver remoteAddrKeyResolver() {
        return exchange -> {
        	//String hostAddress =Objects.requireNonNull( exchange.getRequest().getRemoteAddress().getHostName() );
            String hostAddress = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
            log.info( " -------------- remoteAddrKeyResolver 限流规则 ip ="+ hostAddress );//("remoteAddrKeyResolver 限流规则 ip {}", hostAddress);
            return Mono.just(hostAddress);
        };
    }

    /**
     * 按照 Path 限流
     * @return key
     */
    @Bean(value = "pathKeyResolver")
    public KeyResolver pathKeyResolver() {
        return exchange -> {
            Route route = (Route)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
            log.info(" -------------- pathKeyResolver 限流规则 Path 限流 ="+ route.getId());
            return Mono.just(exchange.getRequest().getPath().toString());
        };
    }
    
	
    @Bean(value = "userKeyResolver")
	public KeyResolver userKeyResolver() {
    	return exchange -> {
    		String userId = Objects.requireNonNull( exchange.getRequest().getQueryParams().getFirst("userId") );
    		log.info("-------------- userKeyResolver 限流规则 userId 限流 ="+ userId );
    		return Mono.just( userId );
    	};
	}
    
    
}
